package net.jueb.majong.core.net.handlerImpl;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import net.jueb.majong.core.net.NetConnection;
import net.jueb.util4j.net.JConnection;

public class NetConntectionAdapter implements NetConnection {
	protected final Map<String,Object> attributes=new HashMap<String,Object>();
	protected final JConnection channel;
	protected int id;
	private Object attachment;

	public NetConntectionAdapter(JConnection channel) {
		this.channel=channel;
		this.id=channel.getId();
	}
		
	public JConnection getChannel() {
		return channel;
	}
	
	@Override
	public int getId() {
		return id;
	}

	@Override
	public boolean isActive() {
		return channel!=null && channel.isActive();
	}

	@Override
	public void close() {
		if(channel!=null && channel.isActive())
		{
			channel.close();
		}
	}

	@Override
	public boolean hasAttribute(String key) {
		return attributes.containsKey(key);
	}

	@Override
	public void setAttribute(String key, Object value) {
		attributes.put(key, value);
	}

	@Override
	public Set<String> getAttributeNames() {
		return attributes.keySet();
	}

	@Override
	public Object getAttribute(String key) {
		return attributes.get(key);
	}

	@Override
	public Object removeAttribute(String key) {
		return attributes.remove(key);
	}

	@Override
	public void clearAttributes() {
		attributes.clear();
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T getAttachment() {
		if(attachment !=null)
		{
			return (T) attachment;
		}
		return null;
	}

	@Override
	public <T> void setAttachment(T attachment) {
		this.attachment=attachment;
	}

	@Override
	public void sendData(byte[] data) {
		if(isActive())
		{
			channel.write(data);
		}
	}

	@Override
	public void sendData(byte[] data, int offset, int count) {
		if(isActive())
		{
			ByteBuf buf=PooledByteBufAllocator.DEFAULT.buffer();
			buf.writeBytes(data, offset, count);
			channel.writeAndFlush(buf);
		}
	}

	@Override
	public void sendMessage(Object message) {
		if(isActive())
		{
			channel.writeAndFlush(message);
		}
	}

	@Override
	public InetSocketAddress getRemote() {
		return channel.getRemoteAddress();
	}

	@Override
	public InetSocketAddress getLocal() {
		return channel.getLocalAddress();
	}

	@Override
	public String getIP() {
		String ip="";
		if(channel!=null)
		{
			InetSocketAddress address=(InetSocketAddress) channel.getRemoteAddress();
			ip=address.getHostString();
		}
		return ip;
	}
	
	@Override
	public String toString() {
		return channel.toString();
	}
}
